<?php

namespace backend\controllers;

use Yii;
use backend\models\Show;
use backend\models\ShowSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use backend\models\Image;
use PHPThumb\GD;
use liangzoe\mobilesmser\TextSmser;
use yii\web\UploadedFile;
use backend\models\PrfConfig;
use yii\web\ForbiddenHttpException;
use backend\models\SysHomeBanner;

/**
 * ShowController implements the CRUD actions for Show model.
 */
class ShowController extends Controller
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }
    public function beforeAction($action)
    {
    	//如果未登录，则直接跳转
    	if(Yii::$app->user->isGuest){
    		return $this->redirect(['/site/login']);
    	}
    
    
    	$action = Yii::$app->controller->action->id;
    	$controller = Yii::$app->controller->id;
    	if(\Yii::$app->user->can('shows-manage')){
    		return true;
    	}else{
    		throw new ForbiddenHttpException(Yii::t('app','Sorry , You don\'t have permission'));
    	}
    }
    /**
     * Lists all Show models.
     * @return mixed
     */
    
    public function actionIndex()
    {
        $searchModel = new ShowSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Show model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
    	$model = $this->findModel($id);
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Show model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Show();

        if (Yii::$app->request->isPost && $model->load(Yii::$app->request->post())) {
        	
        	if($model->top_time_1 === '1'){$model->top_time = time();}//置顶
        	if($model->top_time_1 === '0'){$model->top_time = 0;}//不置顶
        	
        	$model->publish_uid = Yii::$app->user->identity->id;
        	$model->publish_time = time();

        	
        	$model->image_upload = UploadedFile::getInstance($model, 'image_upload');
        	if ($model->image_upload) {
        		if($model->state == '1') $file_menu = '492';
        		if($model->state == '2') $file_menu = '493';
        		if($model->state == '3') $file_menu = '494';
        		if($model->state == '4') $file_menu = '495';
        		
        		$arr = Image::save_image_to_files($model, $file_menu, $model->name, 'show_image_thumb', 'show_image_small');
        		$model->img_small_id = $arr['img_small_id'];
        		$model->img_thumb_id = $arr['img_thumb_id'];
        		$model->img_url_id = $arr['img_url_id'];
        		
        		$model->image_upload = '';
        	}
        	
            if($model->save())return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Show model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
		empty($model->top_time)?$model->top_time_1='0':$model->top_time_1='1';
        if ($model->load(Yii::$app->request->post())) {
        	if($model->top_time_1 === '1'){$model->top_time = time();}//置顶
        	if($model->top_time_1 === '0'){$model->top_time = 0;}//不置顶
        	
        	$model->image_upload = UploadedFile::getInstance($model, 'image_upload');
        	if ($model->image_upload) {
        		if($model->state == '1') $file_menu = '492';
        		if($model->state == '2') $file_menu = '493';
        		if($model->state == '3') $file_menu = '494';
        		if($model->state == '4') $file_menu = '495';
        	
        		$arr = Image::save_image_to_files($model, $file_menu, $model->name, 'show_image_thumb', 'show_image_small',$model->img_url_id,$model->img_thumb_id,$model->img_small_id);
        		$model->img_small_id = $arr['img_small_id'];
        		$model->img_thumb_id = $arr['img_thumb_id'];
        		$model->img_url_id = $arr['img_url_id'];
        		$model->image_upload = '';
        	}
        	
           if($model->save()) return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing Show model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Show model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Show the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Show::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
    
    /**
     * 共用--存入数据到文件夹，并获取缩略图，三种图片的id
     * 压缩比例通过配置表设置
     * @param unknown $model
     * @param number $width1
     * @param number $height1
     * @param number $width2
     * @param number $height2
     * @return multitype:string boolean Ambigous <boolean, number>
     */
    /*
    public function save_image_to_files($model,$file_menu,$image_name,$thumb_type,$small_type)
    {
    	 
    
    	$uuid = md5(uniqid());
    	$uuid_a =  substr($uuid, 0,3);
    	$uuid_b =substr($uuid, 3,3);
    	$uuid_c = substr($uuid, 6,3);
    	$uuid_d =  substr($uuid, 9,3);
    	$uuid_file_name =  substr($uuid, 12,20);
    	$folder = Yii::getAlias('@webroot').'/images/'.$uuid_a.'/'.$uuid_b.'/'.$uuid_c.'/'.$uuid_d;
    	TextSmser::make_dir($folder);
    		
    	$file_save_addr = 'images/'.$uuid_a.'/'.$uuid_b.'/'.$uuid_c.'/'.$uuid_d.'/'.$uuid_file_name; //实际位置
    	$model->file->saveAs(Yii::getAlias('@webroot').'/'.$file_save_addr.'.'.$model->file->extension);
    	if(!empty($model->name)){$image_name = $model->name; }
    	 
    	$image_addr = $file_save_addr.'.'.$model->file->extension;
    	$image_url = $file_menu;
    	$image_w = getimagesize(Yii::getAlias('@webroot').'/'.$file_save_addr.'.'.$model->file->extension)[0];
    	$image_h = getimagesize(Yii::getAlias('@webroot').'/'.$file_save_addr.'.'.$model->file->extension)[1];
    
    	$img_url_id = $this->newimage($image_name,$image_addr, $file_menu, $image_w, $image_h);
    	$img_show = '<img style="margin:20px 10px 0px 0px;width:30%;" src="'.Yii::getAlias('@web').'/'.$file_save_addr.'.'.$model->file->extension.'">';
    	$img_url = $file_save_addr.'.'.$model->file->extension;
    	 
    	$thumb_ratio = PrfConfig::get_config_value($thumb_type); //压缩的比例
    	$small_ratio = PrfConfig::get_config_value($small_type); //压缩的比例
    	//生成缩略图并记录到数据库（中图）,大于990的时候
    	//if( $image_w / 2 >= 990)
    	if( $thumb_ratio >0 )
    	{
    		$thumb = new GD(Yii::getAlias('@webroot').'/'.$file_save_addr.'.'.$model->file->extension); //原图
    		//$thumb->resize($width1,$height1);
    		$thumb->resizePercent($thumb_ratio);
    		$file_save_addr_thumb = $file_save_addr.'_1';//实际位置
    		$thumb->save(Yii::getAlias('@webroot').'/'.$file_save_addr_thumb.'.'.$model->file->extension);
    	  
    		$image_addr_thumb = $file_save_addr_thumb.'.'.$model->file->extension;
    		$image_url_thumb = $file_menu;//虚拟目录（图片类别）
    		$image_w_thumb = getimagesize(Yii::getAlias('@webroot').'/'.$file_save_addr_thumb.'.'.$model->file->extension)[0];
    		$image_h_thumb = getimagesize(Yii::getAlias('@webroot').'/'.$file_save_addr_thumb.'.'.$model->file->extension)[1];
    	  
    		$img_thumb_id = $this->newimage($image_name.'_thumb',$image_addr_thumb, $file_menu, $image_w_thumb, $image_h_thumb);
    		$img_show .= '<img style="margin:20px 10px 0px 0px;" src="'.Yii::getAlias('@web').'/'.$file_save_addr_thumb.'.'.$model->file->extension.'">';
    		$img_thumb_url = $file_save_addr_thumb.'.'.$model->file->extension;
    	}
    	else
    	{
    		$img_thumb_id = $img_url_id;
    	}
    
    	 
    	//生成缩略图并记录到数据库（小图）
    	//if( $image_w /4 >=  300)
    	if( $small_ratio >0 )
    	{
    		//$thumb->resize($width2,$height2);
    		$small = new GD(Yii::getAlias('@webroot').'/'.$file_save_addr.'.'.$model->file->extension);//原图
    		$small->resizePercent($small_ratio);
    		$file_save_addr_small = $file_save_addr.'_2';//实际位置
    		$small->save(Yii::getAlias('@webroot').'/'.$file_save_addr_small.'.'.$model->file->extension);
    		 
    		$image_addr_small = $file_save_addr_small.'.'.$model->file->extension;
    		$image_url_small = $file_menu;//虚拟目录（图片类别）
    		$image_w_small = getimagesize(Yii::getAlias('@webroot').'/'.$file_save_addr_small.'.'.$model->file->extension)[0];
    		$image_h_small = getimagesize(Yii::getAlias('@webroot').'/'.$file_save_addr_small.'.'.$model->file->extension)[1];
    	  
    		$img_small_id = $this->newimage($image_name.'_small',$image_addr_small, $file_menu, $image_w_small, $image_h_small);
    		$img_show .= '<img style="margin:20px 10px 0px 0px;" src="'.Yii::getAlias('@web').'/'.$file_save_addr_small.'.'.$model->file->extension.'">';
    		$img_show = '<div style="text-align:center;'.'">'.$img_show.'</div><div style="text-align:center;color:green;font-weight:bold;font-size:15px;">上传成功！</div>';
    		$img_small_url = $file_save_addr_small.'.'.$model->file->extension;
    
    	}
    	else
    	{
    		$img_small_id= $img_url_id;
    	}
    
    	return array('img_url_id'=>$img_url_id,'img_thumb_id'=>$img_thumb_id,'img_small_id'=>$img_small_id,'img_show'=>$img_show);
    
    }*/
    /**
     * 共用-在数据表sys_image写入新图片
     * @param unknown $image_addr
     * @param unknown $image_url
     * @param unknown $image_w
     * @param unknown $image_h
     * @return boolean
     */
    /*
    public function newimage($image_name,$image_addr,$file_menu,$image_w,$image_h)
    {
    	$model_image = new Image();
    	$model_image->name = $image_name;
    	$model_image->url = $image_addr;
    	$model_image->type = $file_menu;
    	$model_image->width = $image_w;
    	$model_image->height = $image_h;
    	$model_image->update_time = time();
    	if($model_image->save())
    	{
    		return $model_image->id;
    
    	}
    }
    */
    
    public function actionToBanner($id)
    {
    	$this->layout = 'main_small';
    	/*检查是否已存在*/
    	$banner_if_exist = SysHomeBanner::findOne(['action_id'=>$id,'action'=>'show']);
    	if($banner_if_exist != null){
    		
    		//return $this->redirect(Yii::$app->request->referrer);
    		return $this->render('to_banner',[
    				'info' =>'选择的秀家，已加入banner，不能重复添加',
    				]);
    		 
    	}
    	$model_banner = new SysHomeBanner();
    	$model_show = $this->findModel($id);
    	$model_banner->type = 2;
    	$model_banner->name= $model_show->name;
    	$model_banner->designer_id = $model_show->publish_uid;
    	$model_banner->img_small_id =$model_show->img_small_id;
    	$model_banner->img_thumb_id = $model_show->img_thumb_id;
    	$model_banner->img_url_id = $model_show->img_url_id;
    	$model_banner->create_time = time();
    	$model_banner->top_time = time();
    	$model_banner->useing = 1 ;
    	$model_banner->action = 'show';
    	$model_banner->action_id = $id;
    	if($model_banner->save()){
    		return $this->render('to_banner',[
    				'info' =>'成功添加到推荐',
    				]);
    	}
    }
    /**
     * 生成设计+二维码
     */
    public function actionGenerateQrcode(){
    
    	if(Yii::$app->request->isPost){
    		$ids = Yii::$app->request->post("ids");
    		if($ids){
    			foreach ($ids as $val){
    				Show::generateQRcode($val);
    			}
    		}
    		exit(json_encode(array('code'=>'1','msg'=>'已生成二维码')));
    	}
    }
}
